using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Hosting;
using System.Xml;
using System.Xml.Xsl;

namespace Xmlt.ViewEngine
{

    public class XmltTemplate
    {
        public XslCompiledTransform XslTransformer { get; private set; }
        public string TransformText { get; private set; }

        public XmltTemplate(VirtualPathProvider virtualPathProvider, string viewPath)
        {

            if (virtualPathProvider == null)
            {
                throw new ArgumentNullException("virtualPathProvider");
            }

            XslTransformer = XsltTransformCache.Get(viewPath);

            var settings = new XmlReaderSettings { ProhibitDtd = false, ValidationType = ValidationType.None, CloseInput = true };

            if (XslTransformer == null)
            {
                XslTransformer = new XslCompiledTransform();
                if (viewPath.EndsWith(".xml") || viewPath.EndsWith(".xmlt"))
                {
                    XmlVirtualPathResolver resolver = new XmlVirtualPathResolver(Path.GetDirectoryName(System.Web.HttpContext.Current.Server.MapPath(viewPath)));
                    using (var xmlReader = ProcessedXmlHelper.CreateProcessedXmlStream(virtualPathProvider.GetFile(viewPath).Open(), resolver))
                    {
                        XslTransformer.Load(xmlReader, new XsltSettings { EnableDocumentFunction = true, EnableScript = true }, null);
                        List<string> dependencies = new List<string>(resolver.ReferencedUris);
                        System.Web.Caching.CacheDependency cacheDependency = new System.Web.Caching.CacheDependency(
                            dependencies.ToArray(), null, virtualPathProvider.GetCacheDependency(viewPath, new string[] { viewPath }, DateTime.Now));
                        XsltTransformCache.Set(viewPath, XslTransformer, cacheDependency);
                    }
                } 
                else
                {
                    using (var viewSourceStream = virtualPathProvider.GetFile(viewPath).Open())
                    {
                        using (var xmlReader = XmlReader.Create(viewSourceStream, settings))
                        {
                            XmlVirtualPathResolver resolver = new XmlVirtualPathResolver(Path.GetDirectoryName(System.Web.HttpContext.Current.Server.MapPath(viewPath)));
                            XslTransformer.Load(xmlReader, new XsltSettings { EnableDocumentFunction = true, EnableScript = true }, resolver);
                            XsltTransformCache.Set(viewPath, XslTransformer, virtualPathProvider.GetCacheDependency(viewPath, new[] { viewPath }, DateTime.Now));
                        }
                    }
                }

            }
        }
    }

}
